// #region 引入模块

// 服务端框架 express
const express = require('express')

// 处理 express 中的跨域请求 cors 中间件
const cors = require('cors')

// 处理 express 中 req 中的cookie解析
const cookieParser = require('cookie-parser')

// 数据库管理 mongoose
const mongoose = require('mongoose')

// 路径处理
const path = require('path')

// #endregion

// #region 配置express 

// 创建app
const app = express()

// 设置跨域中间件 cors
app.use(cors({credentials: true, origin: true})) // 内部的参数解决了cookie无法设置的问题

// 设置解析 post 请求的请求体的中间件
app.use(express.json())

// 使用vue3开发的静态资源
app.use(express.static(path.join(__dirname, 'dist')))

// #endregion

// #region 配置mongoose 
// 连接服务器
mongoose.connect('mongodb://127.0.0.1:27017/outfit-free')
.then(() => {
  console.log('mongodb connect successfully')
})
.catch(() => {
  console.log('fail to connect mongodb')
})

// 创建merchandises的Schema约束对象
const merchandiseSchema = new mongoose.Schema({
  name: String,
  description: String,
  specification: 
  {
    subscribe1: String,
    subscribe2: String,
    subscribe3: String,
  },
  imageURL: String,
  route: String
})
// 创建users的Schema约束对象
const userSchema = new mongoose.Schema({
  email: String,
  phone: String,
  name: String,
  password: String,
  subscribe: [{
    name: String,
    startDay: Date,
    subscribe: String
  }]
})

// 创建merchandises的Model操作对象
const merchandiseModel = mongoose.model('merchandises', merchandiseSchema)
// 创建users的Model操作对象
const userModel = mongoose.model('users', userSchema)

// #endregion

// #region 后端路由
// 获取全部商品
app.get('/merchandises', (req, res) => {
  merchandiseModel.find().then(data => {
    res.json(data)
  }).catch(err => {
    console.log("fail to find", err)
  })
})

// 获取某个商品
app.get('/get-one-merchandise', (req, res) => {
  merchandiseModel.findById(req.query.id).then(data => {
    res.json(data)
  })
})

// 测试用增加商品
app.post('/merchandises', (req, res) => {
  console.log(req.body)
  res.end('have received json')
  const doc = new merchandiseModel(req.body)
  doc.save()
})

// 获取用户信息
app.get('/users', (req, res) => {
  userModel.findById(req.query.userID).then(data => {
    res.json(data)
  })
})

// 订购商品表单提交
app.post('/subscribe', (req, res) => {
  userModel.updateOne({_id: req.body.userID}, {$push : {subscribe: {
    name: req.body.name,
    startDay: new Date(),
    subscribe: req.body.subscribe
  }}}).then(() => {
    console.log(`subscribe ${req.body.name} success`)
  }).catch(() => {
    console.log('subscribe fail')
  })
  res.end(`subscribe ${req.body.name} for ${req.body.subscribe}`)
})

// 用户注册
app.post('/register', (req, res) => {
  const doc = new userModel(req.body)
  doc.save()
  res.end('user register successfully, please login')
})

// 用户登录
app.post('/login', (req, res) => {
  const userInfo = {
    account: req.query.account,
    password: req.query.password,
  }
  userModel.findOne({email: userInfo.account})
    .then(doc => {
      if (userInfo.password === doc.password) {
        // 将用户id存放到userInfo中
        userInfo.id = doc._id
        // 在res.cookie第二个参数中，如果不是字符串，将多出j:
        res.cookie('cookie', JSON.stringify(userInfo), {
          maxAge: 1000 * 60 * 60 * 24 * 7, // 过期时间为七天
        })
        res.json({
          message: 'user cookie set successfully',
          check: true
        })
      } else {
        res.json({
          message: 'user password error',
          check: false
        })
      }
    })
    .catch(() => {
      res.json({
        message: 'can not find user',
        check: false
      })
    })
})

// 用户退出登录
app.delete('/users', (req, res) => {
  res.clearCookie('cookie').end('exit successfully')
})

// 修改用户信息
app.put('/users', (req, res) => {
  const userInfo = req.query
  userModel.findByIdAndUpdate(userInfo.id, {
    email: userInfo.data.email,
    phone: userInfo.data.phone,
    name: userInfo.data.name,
    password: userInfo.data.password
  }).then(() => {
    res.clearCookie('cookie')
    res.end('set user info successfully, please relogin')
  }).catch(() => {
    res.end('failed to set user info')
  })
})

// cookie检查
app.get('/cookie', (req, res) => {
  const userInfo = {
    account: req.query.account,
    password: req.query.password
  }
  userModel.findOne({email: userInfo.account})
    .then(doc => {
      if (userInfo.password === doc.password) {
        res.json({check: true})
      } else {
        res.json({check: false})
      }
    })
    .catch(() => {
      res.json({check: false})
    })
})

// #endregion

// #region 启动服务器
app.listen(3000, () => {
  console.log('server start successfully')
})
// #endregion
